<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item>
          <el-input
            size="small"
            style="min-width: 210px"
            v-model="listQuery.name"
            placeholder="工程名称"
            clearable
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            size="small"
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="datas"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        style="width: 100%"
        size="small"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.width : 'center'"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        >
        </el-table-column>
        <el-table-column align="center" label="操作" :width="200">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              v-if="is_super"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getDepositList"
      />
    </el-card>
    <!-- 保证金录入 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="800px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
        size="small"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="工程名称" prop="project">
              <el-select
                v-model="form.project"
                placeholder="工程项目"
                clearable
              >
                <el-option
                  v-for="item in projects"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交保证金日期" prop="pay_date">
              <el-date-picker
                v-model="form.pay_date"
                type="date"
                placeholder="交保证金日期"
                value-format="yyyy-MM-dd"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保证金额" prop="pay_money">
              <el-input
                v-model="form.pay_money"
                placeholder="保证金额"
                clearable
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="退保证金日期" prop="refund_date">
              <el-date-picker
                v-model="form.refund_date"
                type="date"
                placeholder="退保证金日期"
                value-format="yyyy-MM-dd"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退保金额" prop="refund_money">
              <el-input
                v-model="form.refund_money"
                placeholder="退保金额"
                clearable
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact_man">
              <el-input
                v-model="form.contact_man"
                placeholder="联系人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="退保说明" prop="explain">
              <el-input
                v-model="form.explain"
                placeholder="退保说明"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(false)"
          >保存</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getDeposits,
  addDeposit,
  updateDeposit,
  delDeposit,
  getProjectList,
} from "@/api/building";

import { getUserList } from "@/api/user";
import { formatDateTime } from "@/utils/datetime";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  project: null,
  pay_date: null,
  pay_money: null,
  refund_date: null,
  refund_money: null,
  contact_man: null,
  remark: null,
  explain: null,
  user: null,
};

export default {
  name: "Deposit",
  data() {
    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        project: [
          { required: true, message: "请选择工程项目", trigger: "blur" },
        ],
      },

      tableColumns: [
        {
          key: "project_name",
          title: "工程名称",
          align: "left",
          width: "200px"
        },
        {
          key: "pay_date",
          title: "交保证金日期",
          width: "130",
        },
        {
          key: "pay_money",
          title: "保证金额(元)",
          width: "120",
        },
        {
          key: "refund_date",
          title: "退保证金日期",
          width: "130",
        },
        {
          key: "refund_money",
          title: "退保金额(元)",
          width: "120",
        },
        {
          key: "contact_man",
          title: "联系人",
          width: "130",
        },
        {
          key: "remark",
          title: "备注",
        },
        {
          key: "explain",
          title: "退保说明",
          align: "left",
        },
      ],
      title: "保证金",

      dialogVisible: false,

      dialogType: "new",
      datas: [],
      projects: [],
      total: 0,
      listLoading: true,

      listQuery: {
        page: 1,
        page_size: 20,
        name: null,
        search_date: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid", "is_super"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getDepositList();
    this.getAllProject();
  },
  methods: {
    getDepositList() {
      this.listLoading = true;
      getDeposits(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取数据失败!");
          this.listLoading = false;
        });
    },
    getAllProject() {
      getProjectList()
        .then((res) => {
          this.projects = res;
        })
        .catch((error) => {
          this.$message.error("获取工程列表失败!");
        });
    },
    getAllUser() {
      getUserList()
        .then((res) => {
          this.users = res;
        })
        .catch((error) => {
          this.$message.error("读取用户信息失败!");
        });
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getDepositList();
    },

    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);

      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delDeposit(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //格式化
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "pay_money") {
        return row.pay_money && row.pay_money.toFixed(2);
      } else if (column.property == "refund_money") {
        return row.refund_money && row.refund_money.toFixed(2);
      } else {
        return cellValue;
      }
    },
    //
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "pay_money" ||
          column.property === "refund_money"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return prev + curr;
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });

      return sums;
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateDeposit(this.form);
          const index = this.datas.findIndex((v) => v.id === res.id);
          this.datas.splice(index, 1, res);
        } else {
          this.form.user = this.uid;
          res = await addDeposit(this.form);
          const { id } = res;
          if (id > 0) {
            this.datas.unshift(res);
          }
        }

        const { project_name, pay_money, refund_money } = res;
        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>工程名称: ${project_name}</div>
              <div>保证金额: ${pay_money}</div>
              <div>退保金额: ${refund_money}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
</style>